package com.mnxc.gxa.utils;

import com.mnxc.gxa.dto.UserDTO;
import com.mnxc.gxa.entity.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @BelongsProject: hm-dianping
 * @BelongsPackage: com.hmdp.utils
 * @Author: mnxc
 * @CreateTime: 2023-06-10  22:22
 * @Description:
 * @Version: 1.0
 */
public class LoginInterceptor implements HandlerInterceptor {
    // private StringRedisTemplate stringRedisTemplate;

    // public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
    //     this.stringRedisTemplate = stringRedisTemplate;
    // }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        // 1.判断是否需要拦截（ThreadLocal中是否有用户）
        // if(com.mnxc.gxa.utils.UserHolder.getUser() == null){
        if(session.getAttribute("user") == null){
            // 没有，需要拦截，设置状态码
            response.setStatus(401);
            // 拦截
            return false;
        }else{
            //存储用户信息
            UserDTO user = (UserDTO) session.getAttribute("user");
            UserHolder.saveUser(user);
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
